package 网络编程.TCPECHO2;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 石方旭
 * Date: 2022-10-04
 * Time: 22:24
 */
public class TCPEchoServer2 {
    //使用字节流不使用scanner进行转换
    private ServerSocket serverSocket = null;
    public TCPEchoServer2(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        //服务器监听8000端口是否有连接.
        //服务器没有接收到连接之前一直阻塞等待,客户端建立连接,就把连接返回给socket对象
        System.out.println("服务端正在监听8000端口...");
        Socket socket = serverSocket.accept();
        //然后服务端这边接收到连接,给socket对象,然后通过socket对象进行与客户端进行交互
        processService(socket);
    }

    public void processService(Socket socket) throws IOException {
        System.out.println("服务器开始启动!!!");
        System.out.printf("建立连接[%s:%d]\n",socket.getInetAddress().toString()
                ,socket.getPort());
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()){
            while(true){
                //服务器这边读取客户端的请求
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                String request = bufferedReader.readLine();
                //构造响应
                String response = process(request);
                //将响应发送给客户端->使用字符流  利用转换流将字节流转换成字符流
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
                bufferedWriter.write(response);
                bufferedWriter.newLine();//表示结束换行符
                bufferedWriter.flush();//刷新缓冲区
                System.out.printf("[%s:%d] req = %s;rep = %s\n",socket.getInetAddress().toString()
                        ,socket.getPort(),request,response);
            }
        }finally {
            socket.close();
        }
    }

    public static String process(String request){
        return "hello,clint";
    }

    public static void main(String[] args) throws IOException {
        TCPEchoServer2 tcpEchoServer1 = new TCPEchoServer2(8000);
        tcpEchoServer1.start();
    }

}
